<template>
  <section class="signature">
    <div class="signatureBox">
      <div class="canvasBox" ref="canvasHW">
        <canvas
          ref="canvasF"
          @touchstart="touchStart"
          @touchmove="touchMove"
          @touchend="touchEnd"
          @mousedown="mouseDown"
          @mousemove="mouseMove"
          @mouseup="mouseUp"
        >
        </canvas>
        <div class="btnBox">
          <button @click="overwrite">重新签名</button>
          <button @click="commit">提交签名</button>
          <button @click="back">返回</button>
        </div>
      </div>
    </div>
    <img class="imgCanvas" :src="imgUrl" />
  </section>
</template>
 
<script>
import { upload_file } from "@/api/user.js";
export default {
  props: {
    bizType: {
      require: true,
    },
  },
  data() {
    return {
      stageInfo: "",
      imgUrl: "",
      client: {},
      points: [],
      canvasTxt: null,
      startX: 0,
      startY: 0,
      moveY: 0,
      moveX: 0,
      endY: 0,
      endX: 0,
      w: null,
      h: null,
      isDown: false,
      // isViewAutograph: this.$route.query.isViews > 0,
      // contractSuccess: this.$route.query.contractSuccess
    };
  },
  mounted() {
    console.log('初始化');
    let canvas = this.$refs.canvasF;
    // canvas.height = this.$refs.canvasHW.offsetHeight - 500;
    canvas.height = this.$refs.canvasHW.offsetHeight;
    canvas.width = this.$refs.canvasHW.offsetWidth - 2;
    canvas.width = this.$refs.canvasHW.offsetWidth - 2;
    this.canvasTxt = canvas.getContext("2d");

    const imageData = this.canvasTxt.getImageData(0, 0, canvas.width, canvas.height);
    for (let i = 0; i < imageData.data.length; i += 4) {
      // 当该像素是透明的，则设置成白色
      if (imageData.data[i + 3] === 0) {
        imageData.data[i] = 255;
        imageData.data[i + 1] = 255;
        imageData.data[i + 2] = 255;
        imageData.data[i + 3] = 255;
      }
    }
    this.canvasTxt.putImageData(imageData, 0, 0);
    // dataURL = canvas.toDataURL('image/png');

    this.stageInfo = canvas.getBoundingClientRect();
    this.canvasTxt.lineWidth = 3; // 线条宽度
  },
  methods: {
      back(){
          this.overwrite();
          this.$emit('back')
      },
    //mobile
    touchStart(ev) {
      ev = ev || event;
      ev.preventDefault();
      if (ev.touches.length == 1) {
        let obj = {
          x: ev.targetTouches[0].clientX,
          y: ev.targetTouches[0].clientY,
        };
        this.startX = obj.x;
        this.startY = obj.y;
        this.canvasTxt.beginPath();
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(obj.x, obj.y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
        this.points.push(obj);
      }
    },
    touchMove(ev) {
      ev = ev || event;
      ev.preventDefault();
      if (ev.touches.length == 1) {
        let obj = {
          x: ev.targetTouches[0].clientX - this.stageInfo.left,
          y: ev.targetTouches[0].clientY - this.stageInfo.top,
        };
        this.moveY = obj.y;
        this.moveX = obj.x;
        this.canvasTxt.beginPath();
        //   strokeStyle = 'blue';
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(obj.x, obj.y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
        this.startY = obj.y;
        this.startX = obj.x;
        this.points.push(obj);
      }
    },
    touchEnd(ev) {
      ev = ev || event;
      ev.preventDefault();
      if (ev.touches.length == 1) {
        let obj = {
          x: ev.targetTouches[0].clientX - this.stageInfo.left,
          y: ev.targetTouches[0].clientY - this.stageInfo.top,
        };
        this.canvasTxt.beginPath();
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(obj.x, obj.y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
        this.points.push(obj);
      }
    },
    //pc
    mouseDown(ev) {
      ev = ev || event;
      ev.preventDefault();
      if (1) {
        let obj = {
          x: ev.offsetX,
          y: ev.offsetY,
        };
        this.startX = obj.x;
        this.startY = obj.y;
        this.canvasTxt.beginPath();
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(obj.x, obj.y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
        this.points.push(obj);
        this.isDown = true;
      }
    },
    mouseMove(ev) {
      ev = ev || event;
      ev.preventDefault();
      if (this.isDown) {
        let obj = {
          x: ev.offsetX,
          y: ev.offsetY,
        };
        this.moveY = obj.y;
        this.moveX = obj.x;
        this.canvasTxt.beginPath();
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(obj.x, obj.y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
        this.startY = obj.y;
        this.startX = obj.x;
        this.points.push(obj);
      }
    },
    mouseUp(ev) {
      ev = ev || event;
      ev.preventDefault();
      if (1) {
        let obj = {
          x: ev.offsetX,
          y: ev.offsetY,
        };
        this.canvasTxt.beginPath();
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(obj.x, obj.y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
        this.points.push(obj);
        this.points.push({ x: -1, y: -1 });
        this.isDown = false;
      }
    },
    //重写
    overwrite() {
      this.canvasTxt.clearRect(
        0,
        0,
        this.$refs.canvasF.width,
        this.$refs.canvasF.height
      );
      this.points = [];
    },
    //提交签名
    commit() {
      let self = this;
      this.imgUrl = this.$refs.canvasF.toDataURL();
      let file = this.dataURLtoFile(this.imgUrl, "demon.png");
      console.log(file);
      if (file) {
        //  上传签名附件
        let data = new window.FormData();
        data.append("file", file);
        upload_file(data).then((res) => {
          if (res.succeed) {
            this.overwrite();
            this.$emit("writeComplete", res.data, self.bizType, file);
          }
        });
      }
    },
    // base64转file
    dataURLtoFile(url, filename) {
      var arr = url.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        i = bstr.length,
        u8arr = new Uint8Array(i);

      while (i--) {
        u8arr[i] = bstr.charCodeAt(i);
      }

      return new File([u8arr], filename, { type: mime });
    },
    // base64转blob
    dataURLtoBlob(url) {
      var arr = url.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        i = bstr.length,
        u8arr = new Uint8Array(i);

      while (i--) {
        u8arr[i] = bstr.charCodeAt(i);
      }

      return new Blob([u8arr], { type: mime });
    },
  },
};
</script>
 
<style lang="less" scoped>
.signature {
  width: 100vw;
  height: 100vh;
}
.signatureBox {
  width: 80%;
  height: 100%;
  box-sizing: border-box;
  overflow: hidden;
  background: #fff;
  z-index: 100;
  display: flex;
  flex-direction: column;
}
.canvasBox {
  box-sizing: border-box;
  flex: 1;
}
.canvasBox canvas {
  border: 1px solid #7d7d7d;
}
.btnBox {
  padding: 10px;
  text-align: center;
  position: absolute;
  top: 50%;
  right: -250px;
  transform: rotate(-90deg);
}
.btnBox button {
  background: transparent;
  border-radius: 4px;
   height: 70px;
  width: 220px;
  font-size: 14px;
  color: #71b900;
  border: 1px solid #71b900;
  margin-right: 10px;
}
.btnBox button:last-of-type {
  background: #71b900;
  color: #fff;
  border-radius: 4px;
  height: 70px;
  width: 220px;
  border: none;
  font-size: 14px;
  margin-left: 10px;
}
</style>